package com.tangding.hprose.api.server.command.impl.user;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.base.Strings;
import com.tangding.common.exception.GException;
import com.tangding.common.tools.ErrorConstants;
import com.tangding.common.utils.JacksonUtil;
import com.tangding.hprose.api.server.command.Command;
import com.tangding.hprose.api.server.command.Response;
import com.tangding.service.dao.role.PermissionRepository;
import com.tangding.service.dao.role.RoleRepository;
import com.tangding.service.dao.user.UserRepository;
import com.tangding.service.entity.user.User;


/**
 * @description 获取我自己以及被我创建的用户
 *
 * @author Ranger
 * @version 2017年11月30日_下午8:25:00
 *
 */
@Component
public class DelUser implements Command {
	static UserRepository userRepository;
	static RoleRepository roleRepository;
	static PermissionRepository permissionRepository;
	
	@Autowired
	public void setUserRepository(UserRepository userRepository) {
		DelUser.userRepository = userRepository;
	}
	@Autowired
	public void setRoleRepository(RoleRepository roleRepository) {
		DelUser.roleRepository = roleRepository;
	}
	@Autowired
	public void setPermissionRepository(PermissionRepository permissionRepository) {
		DelUser.permissionRepository = permissionRepository;
	}

	@Override
	public Response exe(Object... params) throws GException {
		String uid = JacksonUtil.get(params[0], "cid.selectItem.key", true);
		String u = JacksonUtil.get(params[params.length - 1], "uid", true);
		if (uid.equals(u)) {//不能删除自己
			throw new GException(ErrorConstants.CANNOT_DEL_SELF);
		}
		User user = userRepository.getUserByUid(uid);
		if (user == null) {
			throw new GException(ErrorConstants.USER_NOT_FOUND);
		}
		
		String puid = user.getPuid();
		if (Strings.isNullOrEmpty(puid)) {//是系统超级管理员不能删除
			throw new GException(ErrorConstants.CANNOT_DEL_SUPER_ADMIN);
		}
		
		User puser = userRepository.getUserByUid(puid);
		if (puser == null) {//是系统超级管理员不能删除
			throw new GException(ErrorConstants.CANNOT_DEL_SUPER_ADMIN);
		}
		
		Map<String, User> userMap = userRepository.getUserMap();
		for (Map.Entry<String, User> entry : userMap.entrySet()) {
			User us = entry.getValue();
			String pid = us.getPuid();
			if (uid.equals(pid)) {//找到我的一级下线
				us.setPuid(puid);//设置此用户的上级为我原来的上级
				us.setPname(puser.getName());
				userRepository.updateUser(us);
			}
		}
		
		user.setAvailable(false);
		userRepository.setAvailable(user);
		return doResponseSucc();
	}

}
